from PyQt6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, 
                           QHBoxLayout, QPushButton, QStackedWidget,
                           QLabel, QButtonGroup, QMenu, QSizeGrip,
                           QGraphicsDropShadowEffect, QLineEdit, QMessageBox)
from PyQt6.QtCore import Qt, QSize, QTimer
from PyQt6.QtGui import QIcon, QAction, QColor, QKeySequence
from .pages.novel_page import NovelPage
from .pages.writing_page import WritingPage
from .pages.chat_page import ChatPage
from .pages.settings_page import SettingsPage
from .pages.novel_download_page import NovelDownloadPage
import sys
import subprocess
import os
import json
from PyQt6.QtWidgets import QApplication
from .widgets.add_book_dialog import AddBookDialog
from utils.updater import Updater, UpdateChecker

class TitleBarButton(QPushButton):
    def __init__(self, icon_path=None, tooltip="", parent=None):
        super().__init__(parent)
        self.setFixedSize(32, 32)
        if icon_path:
            self.setIcon(QIcon(icon_path))
            self.setIconSize(QSize(16, 16))
        if tooltip:
            self.setToolTip(tooltip)
        self.setCursor(Qt.CursorShape.PointingHandCursor)
        self.setStyleSheet("""
            QPushButton {
                background: transparent;
                border-radius: 4px;
                padding: 6px;
            }
            QPushButton:hover {
                background: rgba(255, 255, 255, 0.1);
            }
            QPushButton:pressed {
                background: rgba(255, 255, 255, 0.15);
            }
        """)

class NavButton(QPushButton):
    def __init__(self, text, icon_path=None, parent=None):
        super().__init__(parent)
        self.setCheckable(True)
        self.setFixedHeight(36)
        
        # 创建水平布局
        layout = QHBoxLayout(self)
        layout.setContentsMargins(12, 0, 12, 0)
        layout.setSpacing(8)
        
        # 添加图标
        if icon_path:
            self.icon_label = QLabel()
            self.icon_label.setFixedSize(16, 16)
            self.icon_label.setObjectName("navButtonIcon")
            self.icon_label.setPixmap(QIcon(icon_path).pixmap(16, 16))
            layout.addWidget(self.icon_label)
        
        # 添加文本
        self.text_label = QLabel(text)
        self.text_label.setObjectName("navButtonText")
        layout.addWidget(self.text_label)
        layout.addStretch()
        
        self.setCursor(Qt.CursorShape.PointingHandCursor)
        self.setText("")

    def update_icon_color(self, is_dark):
        pass

class MainWindow(QMainWindow):
    # 用于跟踪所有窗口实例
    window_instances = []
    
    def __init__(self):
        super().__init__()
        self.dragging = False
        self.settings_file = 'settings.json'
        
        # 将当前窗口实例添加到跟踪列表
        MainWindow.window_instances.append(self)
        
        # 设置窗口标志，禁用系统菜单
        self.setWindowFlags(
            Qt.WindowType.Window |  # 保持窗口属性
            Qt.WindowType.FramelessWindowHint  # 无边框
        )
        
        # 禁用右键菜单
        self.setContextMenuPolicy(Qt.ContextMenuPolicy.NoContextMenu)
        
        self.init_ui()
        self.init_shortcuts()
        self.init_size_grip()
        self.apply_theme("深色主题")
        self.load_window_state()
        
        # 添加书架刷新的定时器
        self.refresh_timer = QTimer(self)
        self.refresh_timer.timeout.connect(self.delayed_refresh)
        
    def init_ui(self):
        self.setWindowTitle("喵神AI")
        
        # 设置窗口图标
        app_icon = QIcon("resources/icons/app.svg")
        self.setWindowIcon(app_icon)
        
        # 创建主窗口部件
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        
        # 创建主布局
        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)
        main_widget.setLayout(main_layout)
        
        # 创建标题栏右侧按钮 - 移到这里，在create_title_bar之前
        self.minimize_btn = QPushButton()
        self.maximize_btn = QPushButton()
        self.close_btn = QPushButton()
        self.new_window_btn = QPushButton()
        
        # 设置按钮图标
        self.minimize_btn.setIcon(QIcon("resources/icons/minimize.svg"))
        self.maximize_btn.setIcon(QIcon("resources/icons/maximize.svg"))
        self.close_btn.setIcon(QIcon("resources/icons/close.svg"))
        self.new_window_btn.setIcon(QIcon("resources/icons/new-window.svg"))
        
        # 设置按钮大小
        for btn in [self.minimize_btn, self.maximize_btn, self.close_btn, self.new_window_btn]:
            btn.setFixedSize(46, 32)
            btn.setIconSize(QSize(16, 16))
            btn.setCursor(Qt.CursorShape.PointingHandCursor)
            btn.setStyleSheet("""
                QPushButton {
                    background: transparent;
                    border: none;
                    border-radius: 4px;
                    margin: 4px;
                }
                QPushButton:hover {
                    background: rgba(255, 255, 255, 0.1);
                }
                QPushButton:pressed {
                    background: rgba(255, 255, 255, 0.15);
                }
            """)
        
        # 特别设置关闭按钮的悬停样式
        self.close_btn.setStyleSheet("""
            QPushButton {
                background: transparent;
                border: none;
                border-radius: 4px;
                margin: 4px;
            }
            QPushButton:hover {
                background: #E81123;
            }
            QPushButton:pressed {
                background: #F1707A;
            }
        """)
        
        # 连接按钮点击事件
        self.minimize_btn.clicked.connect(self.showMinimized)
        self.maximize_btn.clicked.connect(self.toggle_maximize)
        self.close_btn.clicked.connect(self.close)
        self.new_window_btn.clicked.connect(self.create_new_window)
        
        # 添加顶部导航栏
        title_bar = self.create_title_bar()
        main_layout.addWidget(title_bar)
        
        # 创建内容区布局
        content_layout = QHBoxLayout()
        content_layout.setContentsMargins(0, 0, 0, 0)
        content_layout.setSpacing(0)
        
        # 创建侧边栏
        sidebar = self.create_sidebar()
        content_layout.addWidget(sidebar)
        
        # 创建堆叠窗口
        self.stack = QStackedWidget()
        self.novel_page = NovelPage()
        self.novel_download_page = NovelDownloadPage()
        self.writing_page = WritingPage()
        self.chat_page = ChatPage()
        self.settings_page = SettingsPage()
        
        self.stack.addWidget(self.novel_page)
        self.stack.addWidget(self.novel_download_page)
        self.stack.addWidget(self.writing_page)
        self.stack.addWidget(self.chat_page)
        self.stack.addWidget(self.settings_page)
        
        content_layout.addWidget(self.stack)
        
        # 添加内容区到主布局
        main_layout.addLayout(content_layout)
        
        # 添加版本信息标签
        self.version_label = QLabel()
        self.version_label.setStyleSheet("""
            QLabel {
                color: rgba(255, 255, 255, 0.5);
                font-size: 12px;
                padding: 5px;
            }
        """)
        main_layout.addWidget(self.version_label, 0, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignBottom)
        
        # 初始化更新器
        self.updater = Updater()
        self.show_version()
        
        # 连接书架的添加书籍信号
        self.novel_page.bookshelf.addBookRequested.connect(self.show_add_book_dialog)
        
    def create_title_bar(self):
        title_bar = QWidget()
        title_bar.setObjectName("titleBar")
        title_bar.setFixedHeight(32)
        
        # 创建并保存 toolbar_layout
        self.toolbar_layout = QHBoxLayout(title_bar)
        self.toolbar_layout.setContentsMargins(8, 0, 8, 0)
        
        # Logo和标题
        logo_layout = QHBoxLayout()
        logo_layout.setSpacing(8)
        
        # 创建一个容器来放置logo和标题
        logo_container = QWidget()
        logo_container.setObjectName("logoContainer")
        logo_container_layout = QHBoxLayout(logo_container)
        logo_container_layout.setContentsMargins(8, 0, 8, 0)
        logo_container_layout.setSpacing(8)
        
        logo = QLabel()
        logo_pixmap = QIcon("resources/icons/logo.svg").pixmap(24, 24)
        logo.setPixmap(logo_pixmap)
        
        title = QLabel("喵神AI")
        title.setStyleSheet("""
            font-size: 14px;
            font-weight: bold;
            background: transparent;
            outline: none;
        """)
        
        logo_container_layout.addWidget(logo)
        logo_container_layout.addWidget(title)
        
        # 添加到布局
        self.toolbar_layout.addWidget(logo_container)
        self.toolbar_layout.addStretch()
        
        # 添加更新按钮
        update_btn = QPushButton()
        update_btn.setIcon(QIcon("resources/icons/update.svg"))
        update_btn.setToolTip("检查更新")
        update_btn.clicked.connect(self.check_update)
        update_btn.setStyleSheet("""
            QPushButton {
                background: transparent;
                border: none;
                padding: 5px;
            }
            QPushButton:hover {
                background: rgba(255, 255, 255, 0.1);
            }
        """)
        self.toolbar_layout.addWidget(update_btn)
        
        # 右侧按钮布局
        right_buttons = QHBoxLayout()
        right_buttons.setSpacing(0)
        right_buttons.addWidget(self.minimize_btn)
        right_buttons.addWidget(self.maximize_btn)
        right_buttons.addWidget(self.close_btn)
        right_buttons.addWidget(self.new_window_btn)
        self.toolbar_layout.addLayout(right_buttons)
        
        return title_bar
    
    def create_new_window(self):
        """创建新窗口"""
        try:
            # 创建新窗口
            new_window = MainWindow()
            
            # 继承当前窗口的设置
            if hasattr(self, 'settings_page'):
                new_window.settings_page.load_settings()
            
            # 调整新窗口位置，避免完全重叠
            current_pos = self.pos()
            new_window.move(current_pos.x() + 30, current_pos.y() + 30)
            
            # 显示新窗口
            new_window.show()
            
        except Exception as e:
            print(f"创建新窗口失败: {str(e)}")
    
    def create_sidebar(self):
        sidebar = QWidget()
        sidebar.setObjectName("sidebar")
        sidebar.setFixedWidth(180)  # 减小宽度
        
        layout = QVBoxLayout(sidebar)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)  # 移除间距
        
        # 创建功能按钮组
        button_group = QButtonGroup(self)
        
        # 创建功能按钮
        self.buttons = {
            "小说阅读": NavButton("小说阅读", "resources/icons/book.svg"),
            "小说下载": NavButton("小说下载", "resources/icons/download.svg"),  # 新增下载按钮
            "文本创作": NavButton("文本创作", "resources/icons/edit.svg"),
            "GPT对话": NavButton("GPT对话", "resources/icons/chat.svg"),
            "设置": NavButton("设置", "resources/icons/settings.svg"),
        }
        
        # 添加按钮到侧边栏
        for btn in self.buttons.values():
            layout.addWidget(btn)
            button_group.addButton(btn)
        
        layout.addStretch()
        
        # 连接信号
        self.buttons["小说阅读"].clicked.connect(lambda: self.stack.setCurrentWidget(self.novel_page))
        self.buttons["小说下载"].clicked.connect(lambda: self.stack.setCurrentWidget(self.novel_download_page))  # 新增
        self.buttons["文本创作"].clicked.connect(lambda: self.stack.setCurrentWidget(self.writing_page))
        self.buttons["GPT对话"].clicked.connect(lambda: self.stack.setCurrentWidget(self.chat_page))
        self.buttons["设置"].clicked.connect(lambda: self.stack.setCurrentWidget(self.settings_page))
        
        # 默认选中第一个按钮
        self.buttons["小说阅读"].setChecked(True)
        
        return sidebar
    
    def init_shortcuts(self):
        # 添加快捷键
        minimize_action = QAction("最小化", self)
        minimize_action.setShortcut("Alt+M")
        minimize_action.triggered.connect(self.showMinimized)
        self.addAction(minimize_action)
        
        maximize_action = QAction("最大化", self)
        maximize_action.setShortcut("Alt+X")
        maximize_action.triggered.connect(self.toggle_maximize)
        self.addAction(maximize_action)
        
        close_action = QAction("关闭", self)
        close_action.setShortcut("Alt+F4")
        close_action.triggered.connect(self.close)
        self.addAction(close_action)
        
        # 添加撤销快捷键
        undo_action = QAction("撤销", self)
        undo_action.setShortcut(QKeySequence.StandardKey.Undo)  # Ctrl+Z
        undo_action.triggered.connect(self.undo_action)
        self.addAction(undo_action)
    
    def contextMenuEvent(self, event):
        # 添加右键菜单
        menu = QMenu(self)
        
        minimize_action = menu.addAction("最小化")
        maximize_action = menu.addAction("最大化" if not self.isMaximized() else "还原")
        menu.addSeparator()
        close_action = menu.addAction("关闭")
        
        # 连接动作
        minimize_action.triggered.connect(self.showMinimized)
        maximize_action.triggered.connect(self.toggle_maximize)
        close_action.triggered.connect(self.close)
        
        menu.exec(event.globalPos())
    
    def toggle_maximize(self):
        """切换最大化状态"""
        if self.isMaximized():
            self.showNormal()
            self.maximize_btn.setIcon(QIcon("resources/icons/maximize.svg"))
        else:
            self.showMaximized()
            self.maximize_btn.setIcon(QIcon("resources/icons/restore.svg"))

    def mousePressEvent(self, event):
        # 只有在标题栏区域点击时才允许拖动
        if event.button() == Qt.MouseButton.LeftButton:
            title_bar = self.findChild(QWidget, "titleBar")
            if title_bar and title_bar.geometry().contains(event.pos()):
                self.dragging = True
                self.drag_position = event.globalPosition().toPoint() - self.frameGeometry().topLeft()
                event.accept()

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton:
            self.dragging = False
            event.accept()

    def mouseMoveEvent(self, event):
        # 只有在拖动状态下才处理移动
        if self.dragging and event.buttons() & Qt.MouseButton.LeftButton:
            self.move(event.globalPosition().toPoint() - self.drag_position)
            event.accept()

    def apply_theme(self, theme):
        self.setStyleSheet("""
            /* 全局深色背景 */
            * {
                background-color: #2B2B2B;
                color: #FFFFFF;
            }
            
            /* 标题栏样式 */
            QWidget#titleBar {
                background-color: #1A1A1A;
            }
            QWidget#logoContainer {
                background: transparent;
                outline: none;  /* 移除焦点框 */
            }
            QWidget#logoContainer QLabel {
                color: #FFFFFF;
                background: transparent;
                outline: none;  /* 移除焦点框 */
            }
            
            /* 侧边栏样式 */
            QWidget#sidebar {
                background-color: #2B2B2B;
                border: none;
            }
            
            /* 导航按钮样式 */
            #sidebar QPushButton {
                border: none;
                background-color: transparent;
                margin: 4px 8px;
                padding: 8px 16px;
                text-align: left;
                border-radius: 6px;
            }
            #sidebar QPushButton:hover {
                background-color: #929292;  /* 修改为灰色背景 */
            }
            #sidebar QPushButton:checked {
                background-color: #929292;  /* 修改为灰色背景 */
            }
            #sidebar QLabel#navButtonIcon {
                background: transparent;
            }
            #sidebar QLabel#navButtonText {
                color: rgba(255, 255, 255, 0.7);
                font-size: 14px;
                background: transparent;
            }
            #sidebar QPushButton:checked QLabel#navButtonText {
                color: #FFFFFF;
                font-weight: bold;
            }
            #sidebar QPushButton:hover QLabel#navButtonText {
                color: #FFFFFF;
            }
            
            /* 内容区域样式 */
            QStackedWidget {
                background-color: #2B2B2B;
            }
            
            /* 设置页面样式 */
            QFrame#settingsGroup {
                background-color: rgba(255, 255, 255, 0.05);
                border-radius: 8px;
            }
            QLabel#groupTitle {
                font-size: 16px;
                font-weight: bold;
                color: #FFFFFF;
                background: transparent;
            }
            QFrame#separator {
                background-color: rgba(255, 255, 255, 0.1);
            }
            
            /* 下拉框样式 */
            QComboBox {
                background-color: rgba(255, 255, 255, 0.1);
                border: 1px solid rgba(255, 255, 255, 0.1);
                border-radius: 4px;
                padding: 5px 10px;
                color: #FFFFFF;
            }
            QComboBox:hover {
                border-color: #0C61F2;
            }
            QComboBox::drop-down {
                border: none;
                width: 20px;
            }
            QComboBox::down-arrow {
                image: url(resources/icons/dropdown.svg);
            }
            QComboBox QAbstractItemView {
                background-color: #363636;
                border: 1px solid rgba(255, 255, 255, 0.1);
                selection-background-color: #0C61F2;
                selection-color: #FFFFFF;
            }
            
            /* 移除所有按钮的焦点框 */
            QPushButton {
                outline: none;
            }
        """)

    def init_size_grip(self):
        # 添加窗口大小调整控件
        self.size_grip = QSizeGrip(self)
        self.size_grip.setFixedSize(20, 20)
        
    def resizeEvent(self, event):
        """处理窗口大小改变事件"""
        super().resizeEvent(event)
        # 更新大小调整控件位置
        rect = self.rect()
        self.size_grip.move(
            rect.right() - self.size_grip.width(),
            rect.bottom() - self.size_grip.height()
        )

    def load_window_state(self):
        """加载窗口状态"""
        try:
            if os.path.exists(self.settings_file):
                with open(self.settings_file, 'r', encoding='utf-8') as f:
                    settings = json.load(f)
                    window_state = settings.get('window_state', {})
                    
                    # 恢复窗口大小
                    if 'size' in window_state:
                        width = window_state['size'].get('width', 1200)
                        height = window_state['size'].get('height', 800)
                        self.resize(width, height)
                    
                    # 恢复窗口位置
                    if 'pos' in window_state:
                        x = window_state['pos'].get('x', 100)
                        y = window_state['pos'].get('y', 100)
                        self.move(x, y)
                    
                    # 恢复最大化状态
                    if window_state.get('maximized', False):
                        self.showMaximized()
        except Exception as e:
            print(f"加载窗口状态时出错: {str(e)}")
    
    def save_window_state(self):
        """保存窗口状态"""
        try:
            # 读取现有设置
            settings = {}
            if os.path.exists(self.settings_file):
                with open(self.settings_file, 'r', encoding='utf-8') as f:
                    settings = json.load(f)
            
            # 准备窗口状态数据
            window_state = {
                'maximized': self.isMaximized(),
                'size': {
                    'width': self.width(),
                    'height': self.height()
                },
                'pos': {
                    'x': self.x(),
                    'y': self.y()
                }
            }
            
            # 更新设置
            settings['window_state'] = window_state
            
            # 保存设置
            with open(self.settings_file, 'w', encoding='utf-8') as f:
                json.dump(settings, f, ensure_ascii=False, indent=2)
                
        except Exception as e:
            print(f"保存窗口状态时出错: {str(e)}")
    
    def closeEvent(self, event):
        """重写关闭事件，清理窗口实例"""
        # 从跟踪列表中移除当前窗口
        if self in MainWindow.window_instances:
            MainWindow.window_instances.remove(self)
        
        # 保存窗口状态
        self.save_window_state()
        
        # 调用父类的关闭事件
        super().closeEvent(event)

    def undo_action(self):
        # 获取当前焦点的小部件
        focused_widget = self.focusWidget()
        
        # 如果是文本编辑框，且不是密码输入框，才执行撤销操作
        if isinstance(focused_widget, QLineEdit) and focused_widget.echoMode() != QLineEdit.EchoMode.Password:
            focused_widget.undo()
        # 如果是聊天页面，执行撤销操作
        elif self.stack.currentWidget() == self.chat_page:
            self.chat_page.undo_last_message()
        # 如果是写作页面，执行撤销操作
        elif self.stack.currentWidget() == self.writing_page:
            self.writing_page.undo_last_edit()

    def refresh_novel_page(self):
        """刷新小说页面"""
        if hasattr(self, 'novel_page'):
            # 启动定时器，延迟100ms后刷新
            self.refresh_timer.start(100)
            
    def delayed_refresh(self):
        """延迟刷新，确保数据已经写入"""
        self.refresh_timer.stop()
        if hasattr(self, 'novel_page'):
            # 强制重新加载书架数据
            self.novel_page.load_books()
            # 强制刷新UI
            self.novel_page.bookshelf.refresh_bookshelf()
            # 强制更新布局
            self.novel_page.bookshelf.grid_layout.update()

    def show_add_book_dialog(self):
        """显示添加书籍对话框"""
        try:
            dialog = AddBookDialog(self)
            if dialog.exec():
                book_info = dialog.get_book_info()
                if book_info:
                    self.novel_page.bookshelf.add_new_book(book_info)
        except Exception as e:
            print(f"显示添加书籍对话框失败: {str(e)}")

    def show_version(self):
        """显示版本信息"""
        version = self.updater.get_current_version()
        self.version_label.setText(f"版本 {version}")

    def check_update(self):
        """检查更新"""
        try:
            # 创建更新检查器
            self.update_checker = UpdateChecker(
                self.updater.get_current_version(),
                self.updater.get_update_url()
            )
            
            # 连接信号
            self.update_checker.update_available.connect(self.show_update_dialog)
            self.update_checker.check_finished.connect(self.on_check_finished)
            
            # 开始检查
            self.update_checker.start()
            
        except Exception as e:
            QMessageBox.warning(self, "错误", f"检查更新失败: {str(e)}")

    def show_update_dialog(self, update_info):
        """显示更新对话框"""
        reply = QMessageBox.question(
            self,
            "发现新版本",
            f"发现新版本 {update_info['version']}\n\n"
            f"更新内容：\n{update_info['description']}\n\n"
            "是否现在更新？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            self.start_update(update_info)

    def start_update(self, update_info):
        """开始更新"""
        try:
            if self.updater.download_update(update_info):
                QMessageBox.information(self, "更新完成", "更新已完成，请重启应用。")
            else:
                QMessageBox.warning(self, "更新失败", "下载更新失败，请稍后重试。")
        except Exception as e:
            QMessageBox.warning(self, "错误", f"更新失败: {str(e)}")

    def on_check_finished(self, has_update):
        """更新检查完成的处理"""
        if not has_update:
            QMessageBox.information(self, "检查更新", "当前已是最新版本") 